<template>
  <!-- 报销单填报首页 -->
  <div id="contain" :style="containStyle">
    <a-spin :spinning="mainLoading">
      <header-info></header-info>
      <div>
        <div class="list" v-if="mode !== 'approve' && mode !== 'search'">
          <div class="menu">
            <a-row>
              <a-col
                :span="6"
                v-for="(item,index) in menus"
                :key="index"
                class="image_col"
                @click="menuClick(item)"
              >
                <img :src="item.checked === true ? item.img_select:item.img" class="image_img" />
                <div class="item_text">{{ item.title }}</div>
              </a-col>
            </a-row>
          </div>
          <div class="total">
            <span>
              报销合计
              <span class="total_t">{{ sum }}</span>元
            </span>
          </div>
        </div>
        <div class="card-wrapper" ref="box" :style="cardHeight">
          <a-spin :spinning="spinning">
            <expense-card
              ref="expenseCard"
              :list="list"
              :expensetype="currentType"
              @cardClick="cardClick"
              @mutiSelect="selectChange"
              @refresh="getDataSource(currentType)"
            ></expense-card>
            <div class="add-btn" v-show="mode ==='edit'" :style="{right:(!flag?'25%':'10px')}">
              <img
                src="@assets/expense/icon_add.png"
                @click="addClick"
                style="width: 70px;opacity: 0.8;"
              />
            </div>
          </a-spin>
          <div v-if="noMessage" class="login_img">没有更多信息...</div>
          <div class="button" style="z-index: 999">
            <a-button
              type="primary"
              class="submit-btn"
              @click="openSubmitModal"
              v-show="mode ==='edit'"
              :style="{width:(!flag?'15%':'50%')}"
            >提交</a-button>
            <a-button
              type="primary"
              class="submit-btn"
              @click="openApproveModal"
              v-show="mode ==='approve'"
              :style="{width:(!flag?'15%':'50%')}"
            >审批</a-button>
            <a-button class="submit-btn" style="background-color:#c8c9cc;border-color: #c8c9cc" :style="btnStyle" @click="cancel">返回</a-button>
          </div>
        </div>
      </div>
      <submit-modal
        ref="modal"
        :ids="checked"
        :expensetype="currentType"
        :sum="sum"
        @refresh="getDataSource(currentType)"
        @backTo="cancel"
      ></submit-modal>
      <fillin-evection ref="evection" @close="init" ></fillin-evection>
      <fillin-traffic ref="traffic" @close="init"></fillin-traffic>
      <fillin-meal ref="meal" @close="init"></fillin-meal>
      <fillin-other ref="other" @close="init"></fillin-other>
      <approve-modal
        ref="approve"
        :expensetype="currentType"
        :ids="objApprove"
        @close="approveInit"
      ></approve-modal>
    </a-spin>
  </div>
</template>
<script>
import { query } from '@/api/admin'
import HeaderInfo from './header'
import expenseCard from './cardlist'
import submitModal from './submit_modal'
import fillinEvection from './fillin_evection'
import fillinTraffic from './fillin_traffic'
import fillinMeal from './fillin_meal'
import fillinOther from './fillin_other'
import approveModal from './approve_modal'
import pick from 'lodash.pick'
import { mapGetters } from 'vuex'
export default {
  components: {
    HeaderInfo,
    expenseCard,
    submitModal,
    fillinEvection,
    fillinTraffic,
    fillinMeal,
    approveModal,
    fillinOther
  },
  directives: { scroll },
  data () {
    return {
      menus: [
        {
          type: 'evection',
          img: require('@assets/expense/menu_icon_chailv.png'),
          img_select: require('@assets/expense/menu_icon_chailv_select.png'),
          title: '差旅费',
          checked: true
        },
        {
          type: 'traffic',
          img: require('@assets/expense/menu_icon_jiaotong.png'),
          img_select: require('@assets/expense/menu_icon_jiaotong_select.png'),
          title: '交通费',
          checked: false
        },
        {
          type: 'meal',
          img: require('@assets/expense/menu_icon_canyin.png'),
          img_select: require('@assets/expense/menu_icon_canyin_select.png'),
          title: '餐饮费',
          checked: false
        },
        {
          type: 'other',
          img: require('@assets/expense/menu_icon_qita.png'),
          img_select: require('@assets/expense/menu_icon_qita_select.png'),
          title: '其它费用',
          checked: false
        }
      ],
      sum: 0,
      list: [],
      evectionList: [],
      trafficList: [],
      currentType: 'evection',
      checked: [],
      mode: '',
      spinning: false,
      pageNo: 1,
      noMessage: false,
      url: '',
      btnStyle: {},
      bxdh: undefined,
      bxlx: undefined,
      objApprove: [],
      cardHeight: {},
      mainLoading: false,
      containStyle: {},
      pcContainStyle: {
        width: '30%',
        position: 'absolute',
        left: '40%'
      },
      flag: navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  created () {
    if (!this.flag) {
      Object.assign(this.containStyle, this.pcContainStyle)
    } else {
      this.containStyle = {}
    }
    this.mode = this.$route.query.mode
    const windowHeight = window.innerHeight
    if (this.mode !== 'approve' && this.mode !== 'search') {
      this.cardHeight = { height: windowHeight - 290 + 'px' }
    } else {
      this.cardHeight = { height: windowHeight - 150 + 'px' }
    }
    // const bxdh = this.$route.query.bxdh
    // const bxlx = this.$route.query.bxlx
    this.bxdh = this.$route.query.bxdh
    this.bxlx = this.$route.query.bxlx
    this.currentType =
      this.$route.query.type === undefined
        ? 'evection'
        : this.$route.query.type
    this.init()
    if (this.mode === 'edit' || this.mode === 'approve') {
      if (!this.flag) {
        this.btnStyle = { width: '15%' }
      } else {
        this.btnStyle = { width: '50%' }
      }
    } else {
      if (!this.flag) {
        this.btnStyle = { width: '30%' }
      } else {
        this.btnStyle = { width: '100%' }
      }
    }

    const u = navigator.userAgent
    console.log('u', u)
    const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
    // ios页面输入框失焦要页面重置到顶部
    if (isiOS) { // 判断是否是ios端
      let aflag = false
      document.body.addEventListener('focusin', (e) => {
        console.log('弹起e.relatedTarget', e.relatedTarget)
        console.log('弹起e', e)
        // 软键盘弹起事件
        aflag = true
      })
      document.body.addEventListener('focusout', (e) => {
        // 软键盘关闭事件
        if (aflag) {
          console.log('关闭e', e)
          console.log('页面回到原始位置')
          window.scrollTo({ top: 0, behavior: 'smooth' })
        }
        aflag = false
      })
    }
  },
  mounted () {
    // 滚动条事件监听
    window.addEventListener('scroll', this.lazyLoading, true)
    // 挂载完成后，判断浏览器是否支持popstate
    if (window.history && window.history.pushState) {
      history.pushState(null, null, document.URL)
      window.addEventListener('popstate', this.cancel, false)
    }
  },
  // 页面销毁时，取消监听。否则其他vue路由页面也会被监听
  destroyed () {
    window.removeEventListener('popstate', this.cancel, false)
  },
  methods: {
    init () {
      this.sum = 0
      this.getDataSource(this.currentType ? this.currentType : 'evection')
      this.menus.forEach(menu => {
        if (menu.type !== this.currentType) {
          menu.checked = false
        } else {
          menu.checked = true
        }
      })
    },
    approveInit () {
      this.$router.go(-1)
    },
    /**
     * 获取报销列表
     */
    getDataSource (type) {
      this.sum = 0
      this.currentType = type
      let param = {
        bczt: this.mode === 'edit' ? '1' : '2,3,4,5,6,7',
        staffId: this.userInfo.id
      }
      // const bxdh = this.$route.query.bxdh
      // const bxlx = this.$route.query.bxlx
      if (this.currentType === 'evection') {
        this.url = '/wb/ribs/clfInfo'
      } else if (this.currentType === 'traffic') {
        this.url = '/wb/ribs/jtfInfo'
      } else if (this.currentType === 'meal') {
        this.url = '/wb/ribs/cyfInfo'
      } else if (this.currentType === 'other') {
        this.url = '/wb/ribs/qtInfo'
      }
      /* else if (this.currentType === 'evectionquery' || this.currentType === 'mealquery' || this.currentType === 'trafficquery') {
        this.url = '/wb/ribs/queryDetail'
        param = { 'bxdh': bxdh, 'bxlx': bxlx }
      } */
      if (this.bxdh !== null && this.bxdh !== undefined) {
        param = { bxdh: this.bxdh, bxlx: this.bxlx }
      }
      // this.spinning = true
      query(this.url, 'GET', param, {}).then(res => {
        console.log('**********res', res)
        this.list = res.result.data
        this.handleDates()
        this.calculateSum()
        this.mainLoading = false
      })
    },
    /**
     * 滚动获取数据
     */
    lazyLoading () {
      if (this.$refs.box) {
        const scrollTop = this.$refs.box.scrollTop
        const clientHeight = this.$refs.box.clientHeight
        const scrollHeight = this.$refs.box.scrollHeight
        if (scrollTop + clientHeight >= scrollHeight && !this.noMessage) {
          this.$nextTick(() => {
            this.pageNo++
            let param = {
              bczt: this.mode === 'edit' ? '1' : '2,3,4,5,6,7',
              pageNo: this.pageNo,
              staffId: this.userInfo.id
            }
            // const bxdh = this.$route.query.bxdh
            // const bxlx = this.$route.query.bxlx
            if (this.bxdh !== null && this.bxdh !== undefined) {
              param = { bxdh: this.bxdh, bxlx: this.bxlx, pageNo: this.pageNo }
            }
            query(this.url, 'GET', param, {}).then(res => {
              const data = res.result.data
              data.forEach(item => {
                this.list.push(item)
              })
              if (data.length < 10) {
                this.loading = false
                this.noMessage = true
              }
              this.handleDates()
            })
          })
        }
      }
    },
    handleDates () {
      this.list.forEach(item => {
        // 出差天数 和 费用合计 需要根据基础数据计算
        // item.ccts = moment(item.bcfsj).diff(moment(item.gcfsj), 'day') + 1
        if (
          this.currentType === 'evection' ||
          this.currentType === 'evectionquery'
        ) {
          const data = pick(item, [
            'gjtf',
            // 'bjtf',
            'zsbz',
            'zsje',
            'qtfy',
            'ccbz'
          ])
          let hj = 0
          for (var i in data) {
            hj += parseFloat(data[i] === undefined ? 0 : data[i])
          }
          item.fyhj = hj
        } else {
          item.fyhj = item.je
        }
      })
      // this.spinning = false
    },
    /**
     * 计算合计
     */
    calculateSum () {
      this.sum = 0
      if (this.bxdh !== undefined) {
        this.list.some(item => {
          this.sum =
            (parseFloat(this.sum) * 100 + parseFloat(item.fyhj) * 100) / 100
        })
      } else {
        this.checked.forEach(id => {
          this.list.some(item => {
            if (item.id === id.id) {
              this.sum =
                (parseFloat(this.sum) * 100 + parseFloat(item.fyhj) * 100) /
                100
            }
          })
        })
      }
    },
    /**
     * 点击菜单
     */
    menuClick (item) {
      this.mainLoading = true
      item.checked = true
      this.currentType = item.type
      this.checked = []
      this.init()
      this.$refs.expenseCard.begin()
    },
    /**
     * 点击卡片
     */
    cardClick (record, operate) {
      let disabledType = false
      if (
        (this.mode === 'search' && record.bczt !== '驳回') ||
        this.mode === 'approve'
      ) {
        disabledType = true
      }
      if (
        this.currentType === 'evection' ||
        this.currentType === 'evectionquery'
      ) {
        /* if ((this.currentType === 'evectionquery') && record.bczt !== '驳回') {
          disabledType = true
        } */
        this.$refs.evection.openModel(record, operate, disabledType)
      } else if (
        this.currentType === 'traffic' ||
        this.currentType === 'trafficquery'
      ) {
        /* if (this.currentType === 'trafficquery' && record.bczt !== '驳回') {
          disabledType = true
        } */
        this.$refs.traffic.openModel(record, operate, disabledType)
      } else if (
        this.currentType === 'meal' ||
        this.currentType === 'mealquery'
      ) {
        /* if (this.currentType === 'mealquery' && record.bczt !== '驳回') {
          disabledType = true
        } */
        this.$refs.meal.openModel(record, operate, disabledType)
      } else {
        this.$refs.other.openModel(record, operate, disabledType)
      }
    },
    /**
     * 新增报销
     */
    addClick () {
      this.cardClick({}, 'add')
    },
    /**
     * 提交
     */
    openSubmitModal () {
      if (this.checked.length === 0 && this.bxdh === undefined) {
        this.$message.info('请先选择准备报销的单据')
      } else if (this.bxdh !== undefined) {
        if (this.currentType === 'evection') {
          if (this.list.length === 1) {
            this.$message.info('当前选择单据尚未完成闭环，请重新选择')
            return
          } else {
            let paramList = this.list
            // paramList.sort((a, b) => new Date(a.gcfsj) - new Date(b.gcfsj))
            paramList = this.listSort(paramList, true, 'gcfsj')
            if (paramList[0].gcfd !== paramList[paramList.length - 1].gmdd) {
              this.$message.info('当前选择单据最初出发城市与最终目的城市不一致，请重新选择')
              return
            }
          }
        }
        const ids = []
        this.list.some(item => {
          ids.push(item.id)
        })
        this.calculateSum()
        this.checked = ids
        this.$refs.modal.begin(ids)
      } else if (this.bxdh === undefined) {
        if (this.currentType === 'evection') {
          if (this.checked.length === 1) {
            this.$message.info('当前选择单据尚未完成闭环，请重新选择')
            return
          } else {
            let paramList = this.checked
            // paramList.sort((a, b) => new Date(a.gcfsj) - new Date(b.gcfsj))
            paramList = this.listSort(paramList, true, 'gcfsj')
            if (paramList[0].gcfd !== paramList[paramList.length - 1].gmdd) {
              this.$message.info('当前选择单据最初出发城市与最终目的城市不一致，请重新选择')
              return
            }
          }
        }
        const paramIdList = this.checked.map(item => { return item.id })
        this.checked = paramIdList
        this.$refs.modal.begin(this.checked)
      }
    },
    openApproveModal () {
      const param = { type: 'wechat' }
      if (this.mode === 'approve') {
        param.type = 'approve'
      }
      if (this.currentType === 'evection') {
        param.bxlx = '1'
      } else if (this.currentType === 'traffic') {
        param.bxlx = '2'
      } else if (this.currentType === 'meal') {
        param.bxlx = '3'
      } else if (this.currentType === 'other') {
        param.bxlx = '5'
      }
      param.bxdh = this.bxdh
      query('/wb/ribs/approveQuery', 'GET', param, {})
        .then(res => {
          this.objApprove = res.result.data
          this.$refs.approve.begin(this.objApprove)
        })
        .catch(e => {
          this.$notification['info']({
            message: '获取信息失败',
            duration: 4
          })
        })
    },
    selectChange (values) {
      this.checked = values
      this.calculateSum()
    },
    cancel () {
      // this.$router.push({ name: 'appExpenseIndex' })
      // this.$router.go(-1)
      history.back()
    },
    // test () {
    //   const param = {}
    //   param.wechatInfo = { 'accessToken': Vue.ls.get(WX_ACCESS_TOKEN).accessToken, 'wxUserId': Vue.ls.get(WX_USER_ID) }

    //   const actionParam = {// 请求参数
    //     'url': '/wb/ribs/test',
    //     'action': 'post',
    //     'parameter': {},
    //     'data': Object.assign({}, param),
    //     'message': '提交成功'
    //   }
    //   this.confirmLoading = true
    //   method(actionParam).then(res => {
    //   })
    // }

    listSort (arr, sortby, attr) {
      // sortby为true时是正序，sortby为 false时是倒序
      for (let i = 0; i < arr.length - 1; i++) {
        for (let j = i + 1; j < arr.length; j++) {
          if (sortby ? arr[i][attr] > arr[j][attr] : arr[i][attr] < arr[j][attr]) {
            var a = 0
            a = arr[i]
            arr[i] = arr[j]
            arr[j] = a
          }
        }
      }
      return arr
    }
  }
}
</script>
<style lang="less" scoped>
#contain {
  height: 100%;
  background-color: #f2f2f2;
}
.menu {
  height: 90px;
  border-radius: 5px;
  padding: 10px;
  margin: -30px 10px 10px;
  background-color: #ffffff;
  .image_col {
    text-align: center;
    .image_img {
      width: 50px;
      margin: 0px 20px 0px;
    }
  }
}
.total {
  height: 42px;
  line-height: 42px;
  border-radius: 5px;
  margin: 5px 10px 10px;
  background-color: #4499fc;
  text-align: center;
  color: #ffffff;
  font-size: 16px;
  .total_t {
    margin: 0px 10px;
    font-size: 20px;
  }
}
.card-wrapper {
  overflow: scroll;
  .button {
    width: 100%;
    position: fixed;
    bottom: 0;
    .submit-btn {
      width: 50%;
      height: 40px;
    }
  }
  .add-btn {
    bottom: 40px;
    position: fixed;
    right: 10px;
  }
}
.login_img {
  text-align: center;
  color: #cccccc;
  margin-bottom: 20px;
}
.ant-modal {
  top: 10px !important;
}
</style>
